from celery.utils.serialization import jsonify
from django.contrib.messages.api import success
from django.core.paginator import InvalidPage
from django_filters.rest_framework import DjangoFilterBackend
from openpyxl.styles.builtins import total
from rest_framework.decorators import action
from rest_framework import pagination, viewsets
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.permissions import AllowAny

from app.autojob.columns import init_task_columns, install_task_columns
from app.autojob.data_opt import ticket_detail_tree_data, submit_task_data, get_task_log, get_init_script_log, \
    retry_task
from app.autojob.filters import InitTaskListFilter, OSInstallTaskListFilter
from app.autojob.models import InitTaskList, OSInstallTaskList
from app.autojob.serializers import InitTaskListSerializer, OSInstallTaskListSerializer


class AllPagination(pagination.PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 1000

    def paginate_queryset(self, queryset, request, view=None):
        page_size = self.get_page_size(request)
        if not page_size:
            return None

        paginator = self.django_paginator_class(queryset, page_size)
        page_number = self.get_page_number(request, paginator)

        try:
            self.page = paginator.page(page_number)
        except InvalidPage:
            self.page = paginator.page(1)

        if paginator.num_pages > 1 and self.template is not None:
            self.display_page_controls = True

        self.request = request
        return list(self.page)


class InitTaskListViewSet(viewsets.ModelViewSet):
    """物理机"""
    permission_classes = [AllowAny]
    queryset = InitTaskList.objects.all()
    serializer_class = InitTaskListSerializer

    pagination_class = AllPagination

    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterseta_class = InitTaskListFilter
    search_fields = ['systemSN', 'ticketSn', 'businessIp', 'idc', 'is_deleted']

    def list(self, request, *args, **kwargs):
        total = 0
        data = []
        tab = request.query_params.get('tab')
        columns, forms = init_task_columns(tab)
        response = super().list(request, *args, **kwargs)
        if 'results' in response.data:
            data = response.data['results']
            total = response.data['count']
        return jsonify(code=200, success=True, total=total, data=data, columns=columns, forms=forms)

    @action(detail=False, methods=['get'])
    def get_ticket_detail(self, request, *args, **kwargs):
        param = request.query_params
        data = ticket_detail_tree_data(param)
        return jsonify(code=200, success=True, data=data, msg='success')

    @action(detail=False, methods=['post'])
    def submit_ticket_detail(self, request, *args, **kwargs):
        data = request.data
        res, msg = submit_task_data(request, data)
        return jsonify(code=200, success=res, data=[], msg=msg)

    @action(detail=False, methods=['get'])
    def init_task_log(self, request, *args, **kwargs):
        param = request.query_params
        res, msg, data = get_task_log(param)
        return jsonify(code=200, success=res, data=data, msg=msg)

    @action(detail=False, methods=['get'])
    def look_init_script_log(self, request, *args, **kwargs):
        param = request.query_params
        res, msg, data = get_init_script_log(param)
        return jsonify(code=200, success=res, data=data, msg=msg)

    @action(detail=False, methods=['post'])
    def retry_init_task(self, request, *args, **kwargs):
        data = request.data
        res, msg = retry_task(request, data)
        return jsonify(code=200, success=res, data=[], msg=msg)


class OSInstallTaskListViewSet(viewsets.ModelViewSet):
    """物理机"""
    permission_classes = [AllowAny]
    queryset = OSInstallTaskList.objects.all()
    serializer_class = OSInstallTaskListSerializer

    pagination_class = AllPagination

    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = OSInstallTaskListFilter
    search_fields = ['systemSN', 'ticketSn', 'businessIp', 'dic', 'status', 'is_deleted', 'netEnv']

    def list(self, request, *args, **kwargs):
        total = 0
        data = []
        tab = request.query_params.get('tab')
        columns, forms = install_task_columns(tab)
        response = super().list(request, *args, **kwargs)
        if 'results' in response.data:
            data = response.data['results']
            total = response.data['count']
        return jsonify(code=200, success=True, total=total, data=data, columns=columns, forms=forms)
